<template>
    <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item prop="tableIds" label="源：">
                <el-select v-model="form.tableIds" multiple placeholder="请选择表单">
                    <el-option v-for="item in tableMetaList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="targetTableId" label="目标：">
                <el-select v-model="form.targetTableId" collapse-tags placeholder="请选择表单">
                    <el-option v-for="item in tableMetaList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleClick" :loading="submitLoading">合并数据</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>  
import { bitable } from '@lark-base-open/js-sdk';
import { ElNotification, ElMessage } from 'element-plus';

export default {
    data() {
        return {
            form: {
                tableIds: [],
                targetTableId: ''
            },
            rules: {
                tableIds: [
                    { required: true, message: '请选择', trigger: 'change', type: 'array' }
                ],
                targetTableId: [
                    { required: true, message: '请选择', trigger: 'change' }
                ]
            },
            tableMetaList: [],
            submitLoading: false,
            selection: {}
        }
    },
     mounted() {
        this.init()
    },
    methods: {
        async init() {
            const [tableList, selection] = await Promise.all([bitable.base.getTableMetaList(), bitable.base.getSelection()]);
            this.tableMetaList = tableList;
            this.selection = selection;
            const tableMergeTempData = window.localStorage.getItem('tableMergeTempData_' + this.selection.baseId);
            if (tableMergeTempData) {
                const { tableIds, targetTableId } = JSON.parse(tableMergeTempData);
                this.form.tableIds = tableIds;
                this.form.targetTableId = targetTableId;
            }
        },
        formatCellValue(value, fieldType) {
            switch (fieldType) {
                case 1: // 文本
                    return value?.[0]?.text || '';
                case 2: // 数字
                    return value || '';
                case 3: // 单选
                    return value?.[0]?.text || '';
                case 4: // 多选
                    return value?.map(item => item.text).join(', ') || '';
                case 11: // 人员
                    return value?.map(user => user.name).join(', ') || '';
                case 5: // 日期
                    return value ? new Date(value).toLocaleDateString() : '';
                case 7: // 复选框
                    return value ? '✅' : '❌';
                default:
                    return value;
            }
        },
        async handleClick() {
            this.$refs['form'].validate(async (valid) => {
                this.submit()
            })
        },
        async submit() {
            this.$refs.form.validate(async valid => {
              if (!valid) return
              try {
                this.submitLoading = true;
                const mergeData = []
                for (let i = 0; i < this.form.tableIds.length; i++) {
                    const tableId = this.form.tableIds[i];
                    const table = await bitable.base.getTableById(tableId);
                    const res = await table.getRecords({ pageSize: 100 });
                    const records = res.records.map(record => {
                        const obj = { ...record }
                        delete obj.recordId
                        return obj
                    }
                    );
                    mergeData.push(...records);
                }
                this.mergeRecords = mergeData;

                const targetTable = await bitable.base.getTableById(this.form.targetTableId);
                const recordIds = await targetTable.getRecordIdList()
                if (recordIds.length > 0) {
                    await targetTable.deleteRecords(recordIds);
                }
                await targetTable.addRecords(mergeData);
                
                ElNotification({
                    title: '成功',
                    message: '数据表合并成功',
                    type: 'success'
                })

                const tableMergeTempData = {
                    tableIds: this.form.tableIds,
                    targetTableId: this.form.targetTableId
                }
                window.localStorage.setItem(`tableMergeTempData_${this.selection.baseId}`, JSON.stringify(tableMergeTempData))
                this.submitLoading = false;                   
              }
              catch {
                this.submitLoading = false;
                ElNotification({
                    title: '失败',
                    message: '请检查表结构是否一致',
                    type: 'error'
                })
              }
           
            })

        }
    }
}
</script>
<style lang="">

</style>